package indi.kider.server.applet.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import indi.kider.common.constant.AppUserType;
import indi.kider.common.model.apartment.*;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.employee.Tenant;
import indi.kider.server.apartment.mapper.*;
import indi.kider.server.applet.model.User;
import indi.kider.server.employee.mapper.EmployeeMapper;
import indi.kider.server.employee.mapper.TenantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.vankid.common.model.base.CommonResponse;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@SuppressWarnings("ALL")
@Service
public class NewLockServiceImpl implements NewLockService{

    @Autowired
    private DevLockMapper devLockMapper;

    @Autowired
    private DevLockCardMapper devLockCardMapper;
    @Autowired
    private DevLockFingerprintMapper devLockFingerprintMapper;
    @Autowired
    private DevLockVersionMapper devLockVersionMapper;
    @Autowired
    private DevLockPasswordMapper devLockPasswordMapper;

    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 根据房间ID得到锁信息
     * @param houseId
     * @return
     * @throws Exception
     */
    @Override
    public DevLock getLockInfo(String houseId) throws Exception{
        DevLock devLock = new DevLock();
        devLock.setHouseId(Long.valueOf(houseId));
        List<DevLock> list = devLockMapper.select(devLock);
        //目前一个房间一个锁，如果多个了则报错
        if(list!=null&&list.size()>1){
            throw new Exception("存在多个锁具,联系管理员!");
        }
        return list.get(0);
    }

    /**
     * 根据房间删除锁信息
     * @param houseId
     * @return
     * @throws Exception
     */
    @Override
    public String delLockInfo(String houseId) throws Exception {
        DevLock devLock = new DevLock();
        devLock.setHouseId(Long.valueOf(houseId));
        return devLockMapper.delete(devLock) > 0 ? "ok":"fail";
    }

    /**
     * 更新锁信息
     * @param devLock
     * @return
     * @throws Exception
     */
    @Override
    public String updateLockInfo(DevLock devLock) throws Exception {
        return devLockMapper.updateByPrimaryKeySelective(devLock) > 0 ? "ok":"fail";
    }

    /**
     * 新增卡信息  只限于租客和合作企业
     * @param devLockCard
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String addCard(DevLockCard devLockCard, User user) throws Exception {
        if(Strings.isNullOrEmpty(devLockCard.getCard())){
            throw new Exception("卡信息不能为空！");
        }
        if(Strings.isNullOrEmpty(devLockCard.getLockId()) ){
            throw new Exception("锁具不能为空！");
        }
        checkRight(user);
        Tenant tenant = null;
        //租客
        if(AppUserType.TENANT == user.getType()){
            tenant =  tenantMapper.selectByPrimaryKey(user.getId());
            devLockCard.setOpenCardRemark(Strings.isNullOrEmpty(devLockCard.getOpenCardRemark())?"租客自助开卡":devLockCard.getOpenCardRemark());
            devLockCard.setOpenCardUser(Strings.isNullOrEmpty(devLockCard.getOpenCardUser())?tenant.getName():devLockCard.getOpenCardUser());
            devLockCard.setTenantId(user.getId());
            //管理员
        }else if(AppUserType.COOPERATE == user.getType()){
            if(devLockCard.getTenantId() == null){
                throw new Exception("请选择一个租客");
            }
            Employee employee =  employeeMapper.selectByPrimaryKey(user.getId());
            devLockCard.setOpenCardRemark(Strings.isNullOrEmpty(devLockCard.getOpenCardRemark())?"管理员开卡":devLockCard.getOpenCardRemark());
            devLockCard.setOpenCardUser(Strings.isNullOrEmpty(devLockCard.getOpenCardUser())?employee.getName():devLockCard.getOpenCardUser());
        }
//        判断租客卡片数量是否超过设置数量===============start
        if(tenant==null){
            tenant =  tenantMapper.selectByPrimaryKey(devLockCard.getTenantId());
        }
        int cardCnt = tenant.getCardCnt();
        DevLockCard dc = new DevLockCard();
        dc.setTenantId(tenant.getId());
        dc.setLockId(devLockCard.getLockId());
        dc.setState(1);//有效
        //用户有效卡片数量
        int cnt= devLockCardMapper.selectCount(dc);
        if(cardCnt<=cnt){
            throw new Exception("用户【"+tenant.getName()+"】,已存在"+cnt+"张卡片,不能再新增卡片!");
        }
//        判断租客卡片数量是否超过设置数量=================end
        if(devLockCard.getAddTime() == null){
            devLockCard.setAddTime(new Date());
        }
        if(devLockCard.getOpenCardTime() == null){
            devLockCard.setOpenCardTime(new Date());
        }
        devLockCard.setState(1);
        Integer result = devLockCardMapper.insertSelective(devLockCard);
        return result == 1?"ok":"err";
    }
    /**
     * 验证权限
     * @param user
     * @throws Exception
     */
    private void checkRight(User user) throws Exception {
        int type =  user.getType();
        if(AppUserType.LANDLORD == type||AppUserType.WORKER == type||AppUserType.WAITER == type){
            throw new Exception("暂无权限");
        }
    }
    /**
     * 获取卡信息
     * @param devLockCard
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public CommonResponse getCardInfo(DevLockCard devLockCard, User user) throws Exception {
        checkRight(user);
        JSONObject obj = new JSONObject();
        //租客
        if(AppUserType.TENANT == user.getType()){
            devLockCard.setTenantId(user.getId());
        }else if(AppUserType.COOPERATE == user.getType()){
            devLockCard.setEmployeeId(user.getId());
        }
        devLockCard.setState(1);//有效
        List<DevLockCard> list =   devLockCardMapper.getCardInfo(devLockCard);
        obj.put("list",list);
        if(AppUserType.TENANT == user.getType()){
            //查询租客实际卡片数量
            DevLockCard query = new DevLockCard();
            query.setTenantId(user.getId());
            query.setState(1);
            int realCnt = devLockCardMapper.selectCount(query);
            obj.put("realCnt",realCnt);
            //现在卡片数量
            Tenant t =  tenantMapper.selectByPrimaryKey(user.getId());
            obj.put("maxCnt",t.getCardCnt());
        }else{
            obj.put("realCnt","");
            obj.put("maxCnt","");
        }
        return CommonResponse.buildGetSuccessResponse("返回成功",obj);
    }

    /**
     * 删除卡信息
     * @param devLockCard
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String delCard(DevLockCard devLockCard, User user)  throws Exception{
        Example devLockCardE = new Example(DevLockCard.class);
        if(!Strings.isNullOrEmpty(devLockCard.getLockId())&&devLockCard.getTenantId()!=null){
            devLockCardE.createCriteria().andEqualTo("tenantId",devLockCard.getTenantId()).andEqualTo("lockId",devLockCard.getLockId()).andEqualTo("state",1);
        }
        if(devLockCard.getId() != null){
            devLockCardE.createCriteria().andEqualTo("id",devLockCard.getId()).andEqualTo("state",1);
        }
        DevLockCard devLockCardUp = new DevLockCard();
        devLockCardUp.setState(0);
        if(devLockCard.getClearCardRemark() == null){
            devLockCardUp.setClearCardRemark("管理员销卡");
        }else{
            devLockCardUp.setClearCardRemark(devLockCard.getClearCardRemark());
        }
        if(Strings.isNullOrEmpty(devLockCard.getClearCardUser()) ){
            Employee employee = employeeMapper.selectByPrimaryKey(user.getId());
            devLockCardUp.setClearCardUser(employee.getName());
        }else{
            devLockCardUp.setClearCardUser(devLockCard.getClearCardUser());
        }
        if(devLockCard.getClearCardTime() == null){
            devLockCardUp.setClearCardTime(new Date());
        }else{
            devLockCardUp.setClearCardTime(devLockCard.getClearCardTime());
        }
        int result =  devLockCardMapper.updateByExampleSelective(devLockCardUp,devLockCardE);
        return result >= 1?"ok":"err";
    }

    @Override
    public String addFingerprint(DevLockFingerPrint devLockFingerPrint, User user) throws Exception {
        Example devLockFingerPrintE = new Example(DevLockFingerPrint.class);
        if(devLockFingerPrint.getTenantId() == null){
            throw new Exception("请选择一个租客！");
        }
//        判断租客指纹数量是否超过设置数量===============start
        Tenant  tenant =  tenantMapper.selectByPrimaryKey(devLockFingerPrint.getTenantId());
        int tcnt = tenant.getFingerPintCnt();

        DevLockFingerPrint dd=  new DevLockFingerPrint();
        dd.setTenantId(devLockFingerPrint.getTenantId());
        dd.setState(1);
        //用户有效指纹数量
        int cnt= devLockFingerprintMapper.selectCount(dd);
        if(tcnt<=cnt){
            throw new Exception("用户【"+tenant.getName()+"】,已存在"+cnt+"个指纹,不能再新增指纹!");
        }
//        判断租客指纹数量是否超过设置数量=================end

        devLockFingerPrint.setAddTime(new Date());
        devLockFingerPrint.setState(1);
        Integer result = devLockFingerprintMapper.insertSelective(devLockFingerPrint);
        return result == 1?"ok":"err";
    }

    @Override
    public  CommonResponse queryFingerPrint(DevLockFingerPrint devLockFingerPrint, User user) throws Exception {
        JSONObject obj = new JSONObject();
        List<DevLockFingerPrint> devLockFingerPrintList = null;
        //租客
        if(AppUserType.TENANT == user.getType()){
            devLockFingerPrint.setTenantId(user.getId());
            devLockFingerPrintList = devLockFingerprintMapper.select(devLockFingerPrint);
        }else{
            throw new Exception("暂无权限");
        }
        obj.put("list",devLockFingerPrintList);

        //查询租客实际数量
        DevLockFingerPrint query = new DevLockFingerPrint();
        query.setTenantId(user.getId());
        query.setState(1);
        int realCnt = devLockFingerprintMapper.selectCount(query);
        obj.put("realCnt",realCnt);
        //现在数量
        Tenant t =  tenantMapper.selectByPrimaryKey(user.getId());
        obj.put("maxCnt",t.getFingerPintCnt());
        return CommonResponse.buildGetSuccessResponse("返回成功",obj);
    }

    @Override
    public String addLockVersionInfo(DevLockVersion devLockVersion, User user) throws Exception {
        Example devLockVersionE = new Example(DevLockVersion.class);
        devLockVersionE.createCriteria().andEqualTo("lockType",devLockVersion.getLockType()).andEqualTo("state",1);
        List<DevLockVersion> devLockVersionList = devLockVersionMapper.selectByExample(devLockVersionE);
        if(devLockVersionList != null && !devLockVersionList.isEmpty()){
            DevLockVersion devLockVersionUp = new DevLockVersion();
            devLockVersionUp.setState(0);
            devLockVersionUp.setId(devLockVersionList.get(0).getId());
            devLockVersionMapper.updateByPrimaryKeySelective(devLockVersionUp);
        }
        if(devLockVersion.getUpTime() == null){
            devLockVersion.setUpTime(new Date());
        }
        devLockVersion.setState(1);
        Integer result = devLockVersionMapper.insertSelective(devLockVersion);
        return result == 1?"ok":"err";
    }

    @Override
    public List<DevLockVersion> queryLockVersionInfo(DevLockVersion devLockVersion, User user) throws Exception {
        return devLockVersionMapper.select(devLockVersion);
    }

    @Override
    public String addLockPassword(DevLockPassword devLockPassword, User user) throws Exception {
        //        判断租客锁密码数量是否超过设置数量===============start
        Tenant tenant =  tenantMapper.selectByPrimaryKey(devLockPassword.getTenantId());
        int pwdCnt = tenant.getPwdCnt();
        DevLockPassword dd = new DevLockPassword();
        dd.setTenantId(tenant.getId());
        dd.setLockId(devLockPassword.getLockId());
        dd.setState(1);//有效
        int cnt= devLockPasswordMapper.selectCount(dd);
        if(pwdCnt<=cnt){
            throw new Exception("用户【"+tenant.getName()+"】,已存在"+cnt+"个密码,不能再新增密码");
        }
//        判断租客锁密码数量是否超过设置数量=================end
        devLockPassword.setAddTime(new Date());
        devLockPassword.setState(1);
        Integer result = devLockPasswordMapper.insertSelective(devLockPassword);
        return result == 1?"ok":"err";
    }

    @Override
    public  CommonResponse queryLockPassword(DevLockPassword devLockPassword, User user) throws Exception {
        JSONObject obj = new JSONObject();
        List<DevLockPassword> devLockPasswordList = null;
        //租客
        if(AppUserType.TENANT == user.getType()){
            devLockPassword.setTenantId(user.getId());
            devLockPasswordList = devLockPasswordMapper.queryLockPassword(devLockPassword);
        }else if(AppUserType.COOPERATE == user.getType()){
            devLockPassword.setEmployeeId(user.getId());
            devLockPasswordList = devLockPasswordMapper.queryLockPassword(devLockPassword);
        }else{
            throw new Exception("暂无权限");
        }
        obj.put("list",devLockPasswordList);
        //查询租客实际数量
        DevLockPassword query = new DevLockPassword();
        query.setTenantId(user.getId());
        query.setState(1);
        int realCnt = devLockPasswordMapper.selectCount(query);
        obj.put("realCnt",realCnt);
        //现在数量
        Tenant t =  tenantMapper.selectByPrimaryKey(user.getId());
        obj.put("maxCnt",t.getPwdCnt());
        return CommonResponse.buildGetSuccessResponse("返回成功",obj);
    }

    @Override
    public String delFingerprint(DevLockFingerPrint devLockFingerPrint, User user) {
        int i = devLockFingerprintMapper.delete(devLockFingerPrint);
        return i > 0 ?"ok":"err";
    }

    @Override
    public String delLockPassword(DevLockPassword devLockPassword, User user) {
        int i = devLockPasswordMapper.delete(devLockPassword);
        return i > 0 ?"ok":"err";
    }
}
